package org.hy.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Iterator;

import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtil {

	public static SqlSessionFactory sqlSessionFactory;
	
	
	static{
		String resource = "mybatis-config.xml";
		InputStream inputStream = null;
		try {
			inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(null != inputStream)inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static SqlSession openSession(){
		return sqlSessionFactory.openSession();
	}
	
	public static SqlSession openSession(boolean autoCommit) {
		return sqlSessionFactory.openSession(true);
	}

	public static Cache getCache(String name) {
		Configuration mybatisConf = sqlSessionFactory.getConfiguration();
		Collection<String> cacheNames = mybatisConf.getCacheNames();
		if(cacheNames.contains(name)){
			return mybatisConf.getCache(name);
		}
		return null;
	}
	
	public static Cache getCache(Class<?> mapperClass) {
		return getCache(mapperClass.getName());
	}
	
	public static boolean isLazyLoadingEnable() {
		return sqlSessionFactory.getConfiguration().isLazyLoadingEnabled();
	}
	
	public static void printCacheInfo() {
		Configuration mybatisConf = sqlSessionFactory.getConfiguration();
		Iterator<String> iter = mybatisConf.getCacheNames().iterator();
		String cacheName;
		Cache cache;
		StringBuilder sb = new StringBuilder();
		System.out.println("cache name\tsize");
		while(iter.hasNext()){
			cacheName = iter.next();
			cache =  mybatisConf.getCache(cacheName);
			
			sb.append(cacheName).append("\t").append(cache.getSize());
			sb.append("\n");
		}
		System.out.println(sb.toString());
		
	}

	
	public static void main(String []args) {
		printCacheInfo();
	}
}
